package com.yang.gateway.filter;

import com.yang.gateway.util.WebFluxUtils;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.cloud.gateway.filter.GatewayFilterChain;
import org.springframework.cloud.gateway.filter.GlobalFilter;
import org.springframework.core.Ordered;
import org.springframework.http.HttpMethod;
import org.springframework.http.server.reactive.ServerHttpRequest;
import org.springframework.http.server.reactive.ServerHttpResponse;
import org.springframework.stereotype.Component;
import org.springframework.web.server.ServerWebExchange;
import org.yang.common.i18n.enums.RI18nEnum;
import reactor.core.publisher.Mono;

/**
 * 全局过滤器
 * @author: lslands
 * @description:
 * @version：v1.0
 * @date: 2024/6/4 16:56
 */
@Slf4j
@Component
@RequiredArgsConstructor
public class GlobalGatewayFilter implements GlobalFilter, Ordered {

    @Override
    public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {
        long startTime = System.currentTimeMillis();
        ServerHttpRequest request = exchange.getRequest();
        ServerHttpResponse response = exchange.getResponse();
        try {
            log.info("全局拦截执行任务");
        } catch (Exception e) {
            return WebFluxUtils.writeErrorResponse(response, RI18nEnum.TOKEN_INVALID);
        }
        //回调
        return chain.filter(exchange.mutate().request(request).build()).then(Mono.fromRunnable(()->{
            log.info("请求URl:{},请求耗时:{} ms", request.getURI(),System.currentTimeMillis() - startTime);
        }));
    }

    @Override
    public int getOrder() {
        return -1;
    }
}
